package core

import (
	"archive/zip"
	ezip "github.com/alexmullins/zip"
	"io"
	"os"
	"path/filepath"
	"strings"
)

// Gunzip zip压缩 srcFile 文件路径，destZip压缩包保存路径
// password 加密密码 如果为空则不加密
func Gunzip(srcFile, destZip, password string) error {
	srcFiles := srcFile
	zipfile, err := os.Create(destZip)
	if err != nil {
		return err
	}
	defer zipfile.Close()
	archive := ezip.NewWriter(zipfile)
	defer archive.Close()

	filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
		if path == srcFile {
			return nil
		}

		if err != nil {
			return err
		}
		header, err := ezip.FileInfoHeader(info)

		if err != nil {
			return err
		}
		path = strings.Replace(path, "\\", "/", -1)
		srcFiles = strings.Replace(srcFiles, "\\", "/", -1)
		header.Name = strings.Replace(path, srcFiles, "", -1)
		header.Name = strings.Trim(header.Name, "/")
		if password != "" {
			header.SetPassword(password)
		}
		if info.IsDir() {
			header.Name += ""
		} else {
			header.Method = zip.Deflate
		}
		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}
		if !info.IsDir() {
			var file *os.File
			file, err = os.Open(path)
			if err != nil {
				return err
			}
			defer file.Close()
			_, err = io.Copy(writer, file)
		}
		return err
	})
	return err
}
